package com.atguigu.yygh.host.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.host.repository.DepartmentRepository;
import com.atguigu.yygh.host.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author DongYu Zhou
 * @date 2022/6/24 18:49
 */
@Service
@SuppressWarnings("all")//压制所有警告
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * @ApiModelProperty(value = "医院编号")
     * @Indexed //普通索引
     * private String hoscode;
     * @ApiModelProperty(value = "科室编号")
     * @Indexed(unique = true) //唯一索引
     * private String depcode;
     */

    @Override
    public void save(Map<String, Object> stringObjectMap) {
        String s = JSON.toJSONString(stringObjectMap);
        Department department = JSON.parseObject(s, Department.class);
//        保存传过来的科室信息 根据 医院编号+科室编号 保证唯一性
      Department targetDepartment=  departmentRepository.getByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if(targetDepartment!=null){
            //3有，更新
            department.setId(targetDepartment.getId());
            department.setUpdateTime(new Date());
            department.setIsDeleted(targetDepartment.getIsDeleted());
            departmentRepository.save(department);
        }else{
            //4没有,新增
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {

//        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
//        Pageable pageable = PageRequest.of((page - 1), limit, sort);
//
//        Department department = new Department();
//        BeanUtils.copyProperties(departmentQueryVo,department);
//
//        ExampleMatcher matching = ExampleMatcher.matching()
//                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
//                .withIgnoreCase(true);
//
//        Example<Department> example = Example.of(department, matching);
//        Page<Department> pageModel = departmentRepository.findAll(example, pageable);
//        return pageModel;

        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);

        Page<Department> pageModel = departmentRepository.findAll(
                Example.of(department, ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true)),
                PageRequest.of((page - 1), limit, sort));
        return pageModel;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department =
                departmentRepository.getByHoscodeAndDepcode(hoscode,depcode);
        if(department==null){
            throw new YyghException(20001,"科室信息有误");
        }
        departmentRepository.deleteById(department.getId());
    }

    //根据医院编号查询医院所有的科室列表
    @Override
    public List<DepartmentVo> getDepVoList(String hoscode) {
        //1创建返回集合对象
        List<DepartmentVo> departmentArrayList = new ArrayList<>();

        //2查询所有科室集合数据
       List<Department> list= departmentRepository.getByHoscode(hoscode);
        //3改造集合数据，根据bigcode分组集合数据
        Map<String, List<Department>> collect = list.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //4遍历封装大科室数据
        //4.1创建封装大科室数据对象，初步封装
        //DepartmentVo bigDepVo = new DepartmentVo();
        for (Map.Entry<String, List<Department>> stringListEntry : collect.entrySet()) {
            DepartmentVo bigDepVo = new DepartmentVo();
            bigDepVo.setDepcode(stringListEntry.getKey());
            bigDepVo.setDepname(stringListEntry.getValue().get(0).getDepname());

            //5封装关联小科室数据
            ArrayList<DepartmentVo> departmentVos = new ArrayList<>();
            //创建小科室 并封装遍历 stream方式
            stringListEntry.getValue().stream().forEach(i -> {
                DepartmentVo deptList = new DepartmentVo();
                deptList.setDepname(i.getDepname());
                deptList.setDepcode(i.getDepcode());
                departmentVos.add(deptList);
            });
            //大科室添加小科室集合
            bigDepVo.setChildren(departmentVos);
            //添加大科室
            departmentArrayList.add(bigDepVo);
        }
        return departmentArrayList;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department byHoscodeAndDepcode = departmentRepository.getByHoscodeAndDepcode(hoscode, depcode);
        if (byHoscodeAndDepcode==null){
            throw  new YyghException(20001,"空");
        }
        return byHoscodeAndDepcode.getDepname();
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getByHoscodeAndDepcode(hoscode, depcode);
    }


}
